# -*- coding:utf-8 -*-
# __author__ : "张百科"
# Date: 2021/1/26 14:10
# File: construction.py
# IDE: PyCharm

from rest_framework.viewsets import GenericViewSet
from serializers.construction import ConstructionSerializer
from models.construction import Construction
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from utils.response.response import BaseResponse
from utils.Decorators.webworkdecorator import WorkDecorator
from utils.response.httpstate import *
from utils.pagination import pagination,pageSerializer
from filters.construction import ConstructionFilter
from rest_framework.decorators import action
from rest_framework.schemas import ManualSchema
from coreapi import Field
import coreschema
import datetime

class ConstructionViewSet(GenericViewSet):

    queryset = Construction.objects.filter(is_delete=0)
    serializer_class = ConstructionSerializer
    filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
    pagination_class =pagination.Pagination
    filter_class = ConstructionFilter
    search_fields = ('community','manager')

    @WorkDecorator(operate="施工现场", message='列表')
    def list(self, request,*args,**kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        page_queryset = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page_queryset, many=True)
        count = self.paginator.page.paginator.count  # 总数
        num = self.paginator.page.paginator.num_pages  # 页数
        page_size = self.paginator.get_page_size(request)  # 每页显示条数
        pageserializer = pageSerializer.Serializer({'count': count, 'page_num': num, 'page_size': page_size})

        return BaseResponse(data=serializer.data,page=pageserializer.data)

    @WorkDecorator(operate="施工现场", message='新增')
    def create(self, request,*args,**kwargs):

        data = request.data
        # 2.创建序列化器
        serializer = self.get_serializer(data=data)
        # 3.校验
        serializer.is_valid(raise_exception=True)
        # 4.保存
        serializer.save()
        # 5.返回响应
        return BaseResponse(data=serializer.data)

    @WorkDecorator(operate="施工现场", message='详情')
    def retrieve(self, request, pk,*args, **kwargs):

        object = Construction.objects.filter(pk=pk).first()

        if object.is_done==1 and object.is_public==1:
            object.read_count+=1
            object.save()
        serializer = self.get_serializer(object)


        # 5.返回响应
        return BaseResponse(data=serializer.data)

    @WorkDecorator(operate="施工现场", message='更新')
    def update(self, request,pk,*args,**kwargs):

        object = Construction.objects.filter(pk=pk).first()
        object_ser = ConstructionSerializer(object, data=request.data)

        if object_ser.is_valid():
            object_ser.save()
            return BaseResponse()
        else:
            return BaseResponse(message='错误', code=CODE_BUSSINESS_ERROR)
        # 5.返回响应

    @WorkDecorator(operate="施工现场", message='更新进度')
    @action(methods=['put'], detail=False, schema=ManualSchema(
        fields=[
            Field(name='id', required=True, location='form', schema=coreschema.Integer(description='施工现场ID')),
            Field(name='flow', required=True, location='form', schema=coreschema.Integer(description='施工流程')),
        ])
            )
    def doNext(self, request, *args, **kwargs):
        postData = request.data
        id = postData['id']
        flow=postData['flow']
        objects = Construction.objects.filter(id=id, is_delete=0)
        if objects:
            object = objects[0]
            process=object.process
            if process == 8:
                return BaseResponse(message='该项目已完工', code=CODE_BUSSINESS_ERROR)
            else:
                object.process = process+1
                object.flow=flow
                object.update_time=datetime.datetime.now()
                if object.process==8:
                    object.is_done=1
                object.save()
            # serializer = self.get_serializer(user, many=False)
                return BaseResponse()
        else:
            return BaseResponse(message='未找到数据', code=CODE_BUSSINESS_ERROR)

    @WorkDecorator(operate="施工现场", message='设置公开')
    @action(methods=['put'], detail=False, schema=ManualSchema(
        fields=[
            Field(name='id', required=True, location='form', schema=coreschema.Integer(description='施工现场ID'))
        ])
            )
    def doPublic(self, request, *args, **kwargs):
        postData = request.data
        id = postData['id']
        objects = Construction.objects.filter(id=id, is_delete=0)
        if objects:
            object=objects[0]
            is_public = object.is_public
            is_done=object.is_done
            if is_done==1:
                if is_public == 1:
                    object.is_public = 0
                else:
                    object.is_public = 1
                object.save()
                return BaseResponse()
            else:
                return BaseResponse(message='项目还未完工无法使用此功能', code=CODE_BUSSINESS_ERROR)
            # serializer = self.get_serializer(user, many=False)

        else:
            return BaseResponse(message='未找到数据', code=CODE_BUSSINESS_ERROR)

    @WorkDecorator(operate="施工现场", message='上传完工图片')
    @action(methods=['put'], detail=False, schema=ManualSchema(
        fields=[
            Field(name='id', required=True, location='form', schema=coreschema.Integer(description='施工现场ID')),
            Field(name='complete_images', required=True, location='form', schema=coreschema.String(description='施工现场图url合集'))
        ])
            )
    def uploadAchieve(self, request, *args, **kwargs):
        postData = request.data
        id = postData['id']
        complete_images=postData['complete_images']
        objects = Construction.objects.filter(id=id, is_delete=0)
        if objects:
            object = objects[0]
            object.complete_images=complete_images
            object.save()
            return BaseResponse()

        else:
            return BaseResponse(message='未找到数据', code=CODE_BUSSINESS_ERROR)

    @WorkDecorator(operate="施工现场", message='删除')
    def destroy(self, request, pk, *args, **kwargs):

        object = Construction.objects.filter(pk=pk).first()
        object.is_delete = 1
        object.save()
        return BaseResponse()
